#ifndef NO_GRAPHIC
#include <stdio.h>
#include "net.h"

struct Net* N_init(char* addres, int port) {
    if(SDLNet_Init()) {
        printf("%s\n", SDLNet_GetError());
        return(NULL);
    }
    struct Net *n = malloc(sizeof(struct Net));
    if(n == NULL) {
        fprintf(stderr, "Failed to alloc net module\n");
        return NULL;
    }
    n->active = true;
    if(SDLNet_ResolveHost(&n->remoteIp, addres, port) < 0) {
        fprintf(stderr, "Ping error: %s\n", SDLNet_GetError());
        n->active = false;
    }
    if((n->client = SDLNet_TCP_Open(&n->remoteIp)) == NULL) {
        fprintf(stderr, "Connect error: %s\n", SDLNet_GetError());
        n->active = false;
    }
    return(n);
}

void N_send(struct Net *n, struct Package pkg) {
    if(n != NULL && n->active) {
        int length = SDLNet_TCP_Send(n->client, &pkg, sizeof(struct Package));
        if(length < sizeof(struct Package)) {
            fprintf(stderr, "Send error: %s\n", SDLNet_GetError());
        }
    }
}

struct Package N_get(struct Net *n) {
    struct Package pkg = { 0 };
    if(n == NULL || !n->active) return pkg;
    SDLNet_TCP_Recv(n->client, &pkg, sizeof(pkg));
    return(pkg);
}

void N_close(struct Net *n) {
    struct Package pkg = (struct Package){.type = P_CLOSE};
    N_send(n, pkg);
    n->active = false;
    SDLNet_Quit();
    if(!SDLNet_SocketReady(n->client) && n->client != NULL) {
        SDLNet_TCP_Close(n->client);
    }
    if(n != NULL) {
        if(n->active) {
            n->active = false;
            free(n);
        }
    }
    n = NULL;
}

#endif
